<?php
namespace tp5_lib\user_access\controller;

use tp5_lib\common\controller\TestBaseController;
use tp5_lib\user\model\UserModel;
use tp5_lib\access\logic\RoleLogic;

class TestController extends TestBaseController
{
    public function index()
    {
        return $this->fetch();
    }
    public function info()
    {
        $user_id=input("user_id");
        $user_model=new UserModel();
        if(!$user = $user_model->db()->where("id",$user_id)->find()){
            $this->error("用户不存在");
        }
        echo "role:". $user["role"] ."\r\n";
        echo "privilege:". $user["privilege"] ."\r\n";
        $role=RoleLogic::instance();
        $privilege=$role->privilege()->clear();
        $role->load($user["role"])->privilege();
        $privilege->accredit($user["privilege"]);
        echo $privilege->stringify() ."\r\n";
        exit;
    }
    public function update()
    {
        $user_id=input("user_id");
        $privilege=input("privilege");
        $user_model=new UserModel();
        if(!$user = $user_model->db()->where("id",$user_id)->find()){
            $this->error("用户不存在");
        }
        $user_model->db()->where("id",$user_id)->setField("privilege",$privilege);
        $this->success();
    }
    public function attach()
    {
        $user_id=input("user_id");
        $role=input("role");
        $user_model=new UserModel();
        if(!$user = $user_model->db()->where("id",$user_id)->find()){
            $this->error("用户不存在");
        }
        if(!empty($user["role"])){
            $role = $user["role"] . "," . $role;
        }
        $user_model->db()->where("id",$user_id)->setField("role",$role);
        $this->success();
    }
    public function detach()
    {
        $user_id=input("user_id");
        $role=input("role");
        $user_model=new UserModel();
        if(!$user = $user_model->db()->where("id",$user_id)->find()){
            $this->error("用户不存在");
        }
        if(empty($user["role"])){
            $this->error("角色不存在");
        }
        $roles=explode(",",$user["role"]);
        $change=false;
        foreach($roles as $index => $item){
            if($item === $role){
                unset($roles[$index]);
                $change=true;
            }
        }
        if(!$change){
            $this->error("角色不存在");
        }
        $role=implode(",",$roles);
        $user_model->db()->where("id",$user_id)->setField("role",$role);
        $this->success();
    }
}
